//
//  IncomeDetailVC.m
//  Cunli
//
//  Created by lilubin on 15/8/14.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "IncomeDetailVC.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "Config.h"
#import "IncomeModel.h"
#import "DetailCell1.h"
#import "DetailCell2.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "ScoringRulesVC.h"

#define pageSize 10
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height



@interface IncomeDetailVC () <UITableViewDataSource, UITableViewDelegate>
{
    NSMutableArray *_datasArray; /*存储收支详情model*/
    NSString * _count; /*总积分*/
    NSString * _today_total; /*今日总积分*/
}

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation IncomeDetailVC

- (void)viewDidLoad {
    
    self.view.backgroundColor=[UIColor whiteColor];
    [super viewDidLoad];
    [self initAllGloableParameters];
    [self initTableView];
    [self registerDetailCell2];
    [self addRefreshAttribute];
    [self reloadDataToNew:YES];
    [self.view setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initAllGloableParameters
{
    _datasArray = [[NSMutableArray alloc] initWithCapacity:1];
}

- (void)registerDetailCell2
{
    UINib *nib2 = [UINib nibWithNibName:@"DetailCell2" bundle:nil];
    [self.tableView registerNib:nib2 forCellReuseIdentifier:@"DetailCell2"];
    
    UINib *nib1 = [UINib nibWithNibName:@"DetailCell1" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"DetailCell1"];
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
}

- (void)initTableView
{
    CGRect newFrame = self.view.frame;
    CGFloat newHeight = newFrame.size.height-64;
    newFrame.size.height = newHeight;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-44) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    [self.view addSubview:_tableView];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"规则说明" style:UIBarButtonItemStylePlain target:self action:@selector(popScoringRules)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.navigationItem.title = @"收入明细";
}

- (void)popScoringRules
{
    ScoringRulesVC *rulesVC = [[ScoringRulesVC alloc] init];
    [self.navigationController pushViewController:rulesVC animated:YES];
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)reloadDataToNew:(BOOL)new
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:4];
    
    NSUInteger page = 1;
    if (!new)  // new = NO 设置page
    {
        page = _datasArray.count/pageSize + 1; //根据当前数据数组中的数据量来判断应该加载第几页
    }
    
    NSString *pageStr = [NSString stringWithFormat:@"%lu", page];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:pageStr forKey:@"page"];
    [CheckParams setObject:@"10" forKey:@"pagesize"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"pointdetail.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"In IncomeDetailVC:%@", result);
        NSString *response = [result objectForKey:@"response"];
        
        if ([response isEqualToString:@"today_detail"]) {
            NSArray *newsList = result[@"today_detail"];
            _count = result[@"count"];
            _today_total = result[@"today_total"];
            //            NSInteger totalCount_today = [_today_total integerValue];
            NSInteger totalCount_today = [result[@"total_count"] integerValue];
            //            NSLog(@"TEST---:%@",newsList[0][@"optxt"]);
            /*
             *思路：判断是否是刷新
             *是：移除dataArray中的数据，重新加载第一页
             *否：加载下一页的数据，并且拼接到已存在的数据数组中
             */
            if (new) {
                if (_datasArray.count != 0) {
                    [_datasArray removeAllObjects]; //刷新时，将已有数据清除，加载最新数据
                }
            }
            
            if (totalCount_today == _datasArray.count)
            {
                [Config showHUDWithText:@"没有更多数据" andImage:@"done"];
                [self.tableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            }
            else
            {
                for(NSDictionary *dataDic in newsList)
                {
                    //                    IncomeModel *newModel = [[IncomeModel alloc] initWithDataDic:dataDic];
                    IncomeModel *newModel = [IncomeModel yy_modelWithJSON:dataDic];
                    [_datasArray addObject:newModel];
                }
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.legendFooter endRefreshing];
                [self.tableView reloadData];
            });
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            [Config showHUDWithText:text andImage:@"error"];
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
        [self.tableView.legendFooter endRefreshing];
    }];
    
}



#pragma mark - UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    
    return _datasArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /*
    if (section == 0) {
        return 15;
    }
     */
    return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        DetailCell1 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"DetailCell1"];
        cell.totalCount = _count;
        NSLog(@"In tableViewCell totalCount:%@", _count);
        cell.todayIncome = _today_total;
        return cell;
    }
    DetailCell2 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"DetailCell2"];
    cell.detailModel = _datasArray[indexPath.row];
    return cell;
}


@end
